<template>
  <div class="edit-page-wrap">
    <Head title="基本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="问题描述" prop="problemState">
            <el-input
              v-model.trim="ruleForm.problemState"
              placeholder="请输入问题描述"
              maxlength="20"
              clearable
            />
          </el-form-item>
          <el-form-item label="展示优先级" prop="showPriority" class="has-tips">
            <el-input
              v-model.trim="ruleForm.showPriority"
              placeholder="请输入展示优先级"
              maxlength="2"
              type="number"
              clearable
            />
            <div class="tip">
              <div class="icon"></div>
              注：请输入0~99数字，数字越小优先级越高，排序靠前
            </div>
          </el-form-item>
          <el-form-item label="问题解答" prop="answer" class="has-tips">
            <QcEditor
              ref="answerRef"
              placeholder-str="请输入问题解答"
              @blur="blurAnswer"
            ></QcEditor>
            <div class="tip">
              <div class="icon"></div>
              注：为不影响移动端展示效果，建议您适当降低图片分辨率（单张图片不超过10M）
            </div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import QcEditor from '@/components/qcQuillEditor/index.vue';
import { FormInstance, FormRules } from 'element-plus';
import { IS_INT_0 } from '@/utils/verify';
import {
  saveProblem,
  updateProblem,
  getProblemDetail,
} from '@/service/apis/market';

const router = useRouter();
const route = useRoute();
const {
  query: { id, parentId },
} = route;

const ruleFormRef = ref<FormInstance>();
const answerRef = ref();

const ruleForm = reactive({
  problemState: '', //问题描述
  showPriority: '', //展示优先级
  answer: '', // 问题解答
});

// const checkAnswer = (rule: any, value: any, callback: any) => {
//   if(value.length>5000)
//   callback();
// };
const rules = reactive<FormRules>({
  problemState: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
  ],
  showPriority: [
    { required: true, message: '请输入展示优先级', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入正确的展示优先级，整数',
      trigger: 'blur',
    },
  ],
  answer: [
    { required: true, message: '请输入问题解答', trigger: ['blur', 'change'] },
    // { validator: checkAnswer, trigger: ['blur', 'change'] },
  ],
});

const blurAnswer = (html: any, str: any) => {
  console.log('sss----', str, Boolean(str));
  ruleForm.answer = str;
  ruleFormRef.value?.validateField('answer');
};

if (id) {
  getProblemDetail({ id: id }).then((res: any) => {
    ruleForm.problemState = res.problemState;
    ruleForm.showPriority = res.showPriority;
    nextTick(() => {
      answerRef.value?.setHTML(res.answer);
      ruleForm.answer = answerRef.value?.getContent();
    });
  });
}

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  ruleForm.answer = answerRef.value?.getContent();
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  const html = answerRef.value?.getHtml();
  console.log('hhh----', html.length);
  if (html.length > 1024 * 1024 * 5) {
    ElMessage({
      showClose: true,
      message: '问题解答内容超管5M',
      type: 'warning',
    });
    return;
  }

  const form = {
    parentId: parentId,
    id: id,
    problemState: ruleForm.problemState,
    showPriority: ruleForm.showPriority,
    answer: html,
  };
  console.log('rr----', form);
  if (id) {
    updateProblem(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    saveProblem(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
onUnmounted(() => {
  window.localStorage.setItem('problemAdd', '1');
});
</script>